#include <QVBoxLayout>
#include <private/combo/cximuticomb/cximuticmbpop.h>
#include <private/combo/cximuticomb/cximuticomb_p.h>

CxiMutiCmbPop::CxiMutiCmbPop(QWidget* parent)
	: QFrame(parent, Qt::Popup)
{
	setFrameShape(Box);
	init();
}
CxiMutiCmbPop::~CxiMutiCmbPop()
{
}
void CxiMutiCmbPop::addItem(const MutiItem& item) const
{
	QSignalBlocker blocker(listWidget);
	QListWidgetItem* listItem = new QListWidgetItem(listWidget);
	listItem->setFlags(listItem->flags() | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsEnabled);
	listItem->setCheckState(Qt::Unchecked);
	listItem->setData(Qt::DisplayRole, item.display);
	QVariant data = QVariant::fromValue(item);
	listItem->setData(Qt::UserRole, data);
}
void CxiMutiCmbPop::onSearch(const QString& search)
{
	for (int i = 0; i < listWidget->count(); ++i)
	{
		const auto item = listWidget->item(i);
		if (item->text().contains(search, Qt::CaseInsensitive))
		{
			item->setHidden(false);
		}
		else
		{
			item->setHidden(true);
		}
	}
}
void CxiMutiCmbPop::onToggleSelectAll(int state)
{
	for (int i = 0; i < listWidget->count(); ++i)
	{
		const auto item = listWidget->item(i);
		if (!item->isHidden())
		{
			item->setCheckState(state ? Qt::Checked : Qt::Unchecked);
		}
		// TODO:添加信号
	}
}
void CxiMutiCmbPop::onItemClicked(QListWidgetItem* item)
{
	if (item->checkState() == Qt::Checked)
	{
		item->setCheckState(Qt::Unchecked);
	}
	else
	{
		item->setCheckState(Qt::Checked);
	}
}
void CxiMutiCmbPop::onItemChanged(QListWidgetItem* item)
{
	emit stateChanged();
}

void CxiMutiCmbPop::init()
{
	initTopSearchBar();
	initBottomView();
	auto* mainLayout = new QVBoxLayout();
	mainLayout->setContentsMargins(0, 0, 0, 0);
	mainLayout->setSpacing(0);
	mainLayout->addLayout(searchBar);
	mainLayout->addWidget(listWidget);
	setLayout(mainLayout);
}
void CxiMutiCmbPop::initTopSearchBar()
{
	searchLineEdit = new QLineEdit(this);
	selectAll = new QCheckBox("全选", this);
	searchBar = new QHBoxLayout();
	searchBar->setContentsMargins(0, 0, 0, 0);
	searchBar->setSpacing(0);
	searchBar->addWidget(selectAll);
	searchBar->addWidget(searchLineEdit);

	connect(searchLineEdit, &QLineEdit::textChanged,
			this, &CxiMutiCmbPop::onSearch);
	connect(selectAll, &QCheckBox::stateChanged,
			this, &CxiMutiCmbPop::onToggleSelectAll);
}
void CxiMutiCmbPop::initBottomView()
{
	listWidget = new QListWidget(this);
	connect(listWidget, &QListWidget::itemClicked,
			this, &CxiMutiCmbPop::onItemClicked);
	connect(listWidget,&QListWidget::itemChanged,
		this,&CxiMutiCmbPop::onItemChanged);
}
